"""
Case Type   : create table as
Case Name   : 源表为分区表，执行create table as
Create At   : 2024/4/16
Owner       : @li-xin12345
Description :
    1、创建分区表
    2、create table as 创建表，查表属性
    3、清理环境
Expect      :
    1、成功
    2、建表成功，查询结果为n代表表无分区属性
    3、成功
History     :
"""

import os
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class CreateTableAsTest(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.tb_name = ['t_cta_0043_01', 't_cta_0043_02']

    def test_create_table_as(self):
        text = '-----step1:创建分区表;expect:成功-----'
        self.log.info(text)
        sql = f"""drop table if exists {self.tb_name[0]};
        create table {self.tb_name[0]}(id int, name text)
        partition by range(id)
        (partition p1 values less than(10),
        partition p2 values less than(maxvalue));
        insert into {self.tb_name[0]} values(generate_series(1,100));
        """
        res = self.pri_sh.execut_db_sql(sql)
        self.log.info(res)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, res,
                      '执行失败：' + text)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, res,
                      '执行失败：' + text)
        self.assertIn('INSERT 0 100', res, '执行失败：' + text)

        text = '-----step2:建表成功，查询结果为n代表表无分区属性;' \
               'expect:建表成功，查询结果为n代表表无分区属性-----'
        self.log.info(text)
        sql = f'drop table if exists {self.tb_name[1]}; ' \
              f'create table {self.tb_name[1]} as select * from' \
              f' {self.tb_name[0]};'
        res = self.pri_sh.execut_db_sql(sql)
        self.log.info(res)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, res,
                      '执行失败：' + text)
        self.assertIn('INSERT 0 100', res, '执行失败：' + text)

        sql = f"select parttype from pg_class where " \
              f"relname = '{self.tb_name[1]}';"
        res = self.pri_sh.execut_db_sql(sql)
        self.log.info(res)
        self.assertEqual(res.splitlines()[-2].strip(), 'n', '执行失败：' + text)

    def tearDown(self):
        text = '-----step3:清理环境;expect:成功-----'
        self.log.info(text)
        for i in self.tb_name:
            sql = f'drop table if exists {i} cascade;'
            res = self.pri_sh.execut_db_sql(sql)
            self.log.info(res)
            self.assertIn(self.constant.TABLE_DROP_SUCCESS, res,
                          '执行失败：' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
